import tkinter as tk
import numpy as np
import _thread
from .pos_direct import GamePosition
from typing import Union


class GameGUI(tk.Tk, object):
    def __init__(self, unit_size: int, maze_map: np.ndarray):
        super().__init__()
        self.width = maze_map.shape[1]
        self.height = maze_map.shape[0]
        self.unit_size = unit_size
        self.player_id: Union[int, None] = None
        self.canvas: tk.Canvas = self.build_maze()
        self.init_mazemap(maze_map)

    def build_maze(self) -> tk.Canvas:
        """
        创建迷宫的函数 不会执行生成用户部分
        :param maze_map: 传入的迷宫数据
        :return:
        """
        UNIT = self.unit_size  # pixels
        MAZE_H = self.height  # grid height
        MAZE_W = self.width  # grid width
        canvas = tk.Canvas(self, bg="white", height=MAZE_H * UNIT, width=MAZE_W * UNIT)
        # create grids
        for c in range(0, MAZE_W * UNIT, UNIT):
            x0, y0, x1, y1 = c, 0, c, MAZE_H * UNIT
            canvas.create_line(x0, y0, x1, y1)
        for r in range(0, MAZE_H * UNIT, UNIT):
            x0, y0, x1, y1 = 0, r, MAZE_W * UNIT, r
            canvas.create_line(x0, y0, x1, y1)
        # create origin
        origin = np.array([20, 20])
        # pack all
        canvas.pack()
        # self.mainloop()
        return canvas

    def init_mazemap(self, maze_map: np.ndarray):
        UNIT = self.unit_size
        canvas = self.canvas
        height = maze_map.shape[0]
        width = maze_map.shape[1]
        for i in range(height):
            pox_y = i * UNIT
            for j in range(width):
                pos_x = j * UNIT
                if maze_map[i][j] == '#':
                    canvas.create_rectangle(
                        pos_x, pox_y,
                        pos_x + UNIT, pox_y + UNIT,
                        fill='black')
                elif maze_map[i][j] == '$':
                    canvas.create_rectangle(
                        pos_x, pox_y,
                        pos_x + UNIT, pox_y + UNIT,
                        fill='yellow')
        self.canvas.pack()

    def start_maze(self, player_pos: GamePosition):
        self.init_player(player_pos)
        self.update()

    def init_player(self, player_pos: GamePosition):
        UNIT = self.unit_size
        canvas = self.canvas
        pos_x = player_pos.x * UNIT
        pos_y = player_pos.y * UNIT
        canvas.delete(self.player_id)
        self.player_id = canvas.create_rectangle(
            pos_x, pos_y,
            pos_x + UNIT, pos_y + UNIT,
            fill='red')
        # pack all
        canvas.pack()

    def display(self, pos: GamePosition):
        self.init_player(pos)
        self.update()
